import {
  Breadcrumb,
  Button,
  Card,
  Form,
  Input,
  message,
  Radio,
  Space,
  Upload,
} from 'antd';
import Channel from 'pages/component/channel';
import { Link } from 'react-router-dom';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import styles from './index.modules.scss';
import Modal from 'antd/lib/modal/Modal';
import { baseURL } from 'unitls/request';
import { getToken } from 'unitls/storage';
import { useState } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { publishArticleAPI } from 'api/article';
import { useHistory } from 'react-router-dom';

export default function ArticlePublish() {
  const [imgUrl, setImgUrl] = useState('');
  const [fileList, setFileList] = useState([]);

  const [type, setType] = useState(1);

  const history = useHistory();

  const props = {
    name: 'image',
    accept: '.jpg,.png,.jpeg',
    action: `${baseURL}/v1_0/upload`,
    headers: {
      authorization: `Bearer ${getToken()}`,
    },
    onChange(info) {
      setFileList(info.fileList);
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
    onPreview(file) {
      console.log('file  ----->  ', file);
      setImgUrl(file.thumbUrl);
    },

    beforeUpload(file) {
      const allowFileType = ['image/jpeg', 'image/jpg', 'image/png'];

      console.log('file  ----->  ', file);
      if (!allowFileType.includes(file.type)) {
        message.warning('不允许上传的文件类型');
        return Upload.LIST_IGNORE;
      }
    },
  };

  const handleSubmit = async (values) => {
    const formData = { ...values };

    formData.cover = {
      type: type,
      images:
        type === 0 ? [] : showFileList.map((item) => item.response.data.url),
    };

    delete formData.type;

    await publishArticleAPI(formData);
    message.success('发布成功', 1);
    history.push('/list');
  };
  const handleValuesChange = (changedValues, allValues) => {
    if (changedValues.type !== undefined) {
      setType(changedValues.type);
    }
  };

  const showFileList = fileList.filter((item, index) => {
    if (type === 0) return false;

    if (type === 1) return index === 0;

    return true;
  });
  return (
    <div style={{ paddingTop: 24 }} className={styles.root}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>发布文章</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          size="large"
          name="basic"
          labelCol={{
            span: 4,
          }}
          wrapperCol={{
            span: 20,
          }}
          autoComplete="off"
          onFinish={handleSubmit}
          initialValues={{
            content: '',
          }}
          onValuesChange={handleValuesChange}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: '请输入文章标题',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="频道"
            name="channel_id"
            rules={[
              {
                required: true,
                message: '请选择频道',
              },
            ]}
          >
            <Channel style={{ width: 200 }}></Channel>
          </Form.Item>

          <Form.Item
            label="内容"
            name="content"
            rules={[
              {
                required: true,
                message: '文章内容不能为空',
              },
              {
                validator: (_, value) => {
                  if (value === '<p><br></p>') {
                    return Promise.reject(new Error('内容不能为空'));
                  }

                  return Promise.resolve();
                },
                message: '文章内容不能为空',
              },
            ]}
          >
            <ReactQuill></ReactQuill>
          </Form.Item>

          <Form.Item label="封面" name="type">
            <Radio.Group>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Upload {...props} listType="picture-card" fileList={showFileList}>
              {fileList.length < type && (
                <Button icon={<UploadOutlined />}></Button>
              )}
            </Upload>
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 4,
            }}
          >
            <Space>
              <Button type="primary" htmlType="submit">
                发布文章
              </Button>

              <Button type="primary" htmlType="submit">
                存草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      <Modal visible={!!imgUrl} onCancel={() => setImgUrl('')} footer={null}>
        <img width={470} src={imgUrl} alt="" />
      </Modal>
    </div>
  );
}
